/**
 * TopTips 顶部错误提示
 * @param {boolean} value 是否显示；默认false
 * @param {string} content 错误提示文字，也可自定义slot
 * @param {number} duration  多少毫秒后关闭，默认2000
 * @param {Function} on-close 关闭的回调
 *
 * @example
 * 1.组件形式引用
 * <TopTips v-model="visible" @close="handleClose">错误提示<TopTips>
 *
 * 2.函数时调用
 * 打开
 * TopTips.show('错误提示')
 * 关闭
 * TopTips.hide()
 */

import Vue from 'vue'
import TopTips from './topTip.vue'

let instance

const data = {
  visible: false,
  content: '',
  duration: 3000
}

function createInstance (properties) {
  const vm = new Vue({
    data: Object.assign({}, data, properties),
    render (h) {
      return h(TopTips, {
        props: {
          value: this.visible,
          content: this.content,
          duration: this.duration
        },
        on: {
          close: () => {
            this.onClose && this.onClose()
            this.remove()
          }
        }
      })
    },
    methods: {
      remove () {
        this.visible = false
        setTimeout(() => {
          this.destroy()
        }, 300)
      },
      destroy () {
        this.$destroy()
        document.body.removeChild(this.$el)
      }
    }
  })

  const component = vm.$mount()
  document.body.appendChild(component.$el)

  return {
    show (props) {
      if (Object.prototype.toString.call(props) === '[object String]') {
        vm.content = props
      } else {
        for (let prop in props) {
          if (props.hasOwnProperty(prop)) {
            vm[prop] = props[prop]
          }
        }
      }
      vm.visible = true
    },
    hide () {
      vm.visible = false
      vm.remove()
    }
  }
}

TopTips.show = props => {
  instance = createInstance(props)
  instance.show(props)
}

TopTips.hide = props => {
  instance && instance.hide()
}

export default TopTips
